package com.srit.system.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.srit.core.bean.Page;
import com.srit.core.sql.BaseResultSetExtractor;
import com.srit.forecast.bean.WeatherCode;
import com.srit.forecast.constant.Constant;
import com.srit.system.bean.Event;
import com.srit.system.dao.EventDao;

/**
 * 事件注册
 * 
 * @author guan
 * 
 */
@Service
@Transactional
public class EventDaoImpl implements EventDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public int getMaxId() {
		String sql = "select max(EVENTID) from TC_EVENT";
		return jdbcTemplate.queryForInt(sql);
	}

	@Override
	public void save(Event t) {
		String sql = "insert into TC_EVENT (EVENTID,EVENTKEY,EVENTDESC,EVENTTARGET,EVENTACTIONCODES)values(SEQ_TC_EVENT.NEXTVAL,?,?,?,?)";
		jdbcTemplate.update(
				sql,
				new Object[] { t.getEventKey(), t.getEventDesc(),
						t.getEventTarget(), t.getEventActionCodes() });
	}

	@Override
	public void update(Event t) {
		String sql = "update TC_EVENT set EVENTKEY=?,EVENTDESC=?,EVENTTARGET=?,EVENTACTIONCODES=? where EVENTID=?";
		jdbcTemplate.update(
				sql,
				new Object[] { t.getEventKey(), t.getEventDesc(),
						t.getEventTarget(), t.getEventActionCodes(),
						t.getEventId() });

	}

	@Override
	public Event getById(Integer id) {
		String sql = "select * from TC_EVENT where EVENTID =?";
		return jdbcTemplate.queryForObject(sql, new Object[] { id },
				new EventRowMapper());
	}

	@Override
	public void delete(Integer id) {

	}

	@Override
	public void page(Page page) {
		String sqlCount = "select count(*) from TC_EVENT where 1=1 ";
		String sqlAnd = " ";
		String sqlSelect = "select t2.* "
				+ "from (select rownum r,t1.* from TC_EVENT t1 where rownum<? "
				+ sqlAnd + ") t2 where t2.r>? order by eventid"; 
		int count = jdbcTemplate.queryForInt(sqlCount + sqlAnd);
		List<WeatherCode> list = jdbcTemplate.query(sqlSelect, new Object[] {
				(page.getPageNum() + 1) * page.getPageSize(),
				page.getPageNum() * page.getPageSize() }, new EventRowMapper());
		page.setCount(count);
		page.setList(list);
	}

}

class EventResultSetExtractor extends BaseResultSetExtractor<Event> {

}

class EventRowMapper implements RowMapper {

	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		EventResultSetExtractor extractor = new EventResultSetExtractor();
		return extractor.extractData(rs);
	}

}
